<?php
require_once dirname(__FILE__) . '/config.php';
require_once 'carrier_map.php';
session_start();

// 创建数据库连接
function getDBConnection() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die('连接失败: ' . $conn->connect_error);
    }
    $conn->set_charset('utf8');
    return $conn;
}

$result = null;
$error = null;

// 获取查询历史
if (isset($_SESSION['user_id'])) {
    $conn = getDBConnection();
    $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE user_id = ? ORDER BY query_time DESC LIMIT 10");
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
    $conn->close();
}

// 支持通过GET参数自动查询
if (empty($_POST) && isset($_GET['tracking_number'])) {
    $_POST['tracking_number'] = $_GET['tracking_number'];
    if (isset($_GET['carrier'])) {
        $_POST['carrier'] = $_GET['carrier'];
    }
    $_SERVER['REQUEST_METHOD'] = 'POST';
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $tracking_number = $_POST['tracking_number'];
    $carrier = isset($_POST['carrier']) ? $_POST['carrier'] : '';
    
    // 调用快递查询API
    $url = API_HOST . API_PATH . "?no=" . urlencode($tracking_number);
    if (!empty($carrier)) {
        $url .= "&type=" . $carrier;
    }
    
    $headers = array("Authorization:APPCODE " . API_APPCODE);
    
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    
    $response = curl_exec($curl);
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    list($header, $body) = explode("\r\n\r\n", $response, 2);
    
    if ($httpCode == 200) {
        $result = json_decode($body, true);
        
        // 获取最新状态
        $latest_status = '';
        if (isset($result['result']['list'][0]['status'])) {
            $latest_status = $result['result']['list'][0]['status'];
        }
        
        // 如果用户已登录，更新查询记录
        if (isset($_SESSION['user_id'])) {
            $conn = getDBConnection();
            
            // 获取API返回的快递公司
            $api_carrier = isset($result['result']['type']) ? $result['result']['type'] : '';
            
            // 检查是否已存在该单号的记录
            $stmt = $conn->prepare("SELECT id FROM tracking_history WHERE user_id = ? AND tracking_number = ?");
            $stmt->bind_param("is", $_SESSION['user_id'], $tracking_number);
            $stmt->execute();
            $existing = $stmt->get_result()->fetch_assoc();
            $stmt->close();
            
            if ($existing) {
                // 更新现有记录
                $stmt = $conn->prepare("UPDATE tracking_history SET carrier = ?, status = ?, query_time = CURRENT_TIMESTAMP WHERE id = ?");
                $stmt->bind_param("ssi", $api_carrier, $latest_status, $existing['id']);
            } else {
                // 插入新记录
                $stmt = $conn->prepare("INSERT INTO tracking_history (user_id, tracking_number, carrier, status) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isss", $_SESSION['user_id'], $tracking_number, $api_carrier, $latest_status);
            }
            $stmt->execute();
            $stmt->close();
            $conn->close();
            
            // 重新获取查询历史
            $conn = getDBConnection();
            $stmt = $conn->prepare("SELECT * FROM tracking_history WHERE user_id = ? ORDER BY query_time DESC LIMIT 10");
            $stmt->bind_param("i", $_SESSION['user_id']);
            $stmt->execute();
            $history = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
            $stmt->close();
            $conn->close();
        }
    } else {
        $error = "查询失败，请检查快递单号是否正确";
    }
    
    curl_close($curl);
}
?>

<style>
:root {
    --primary-color: #4a6bff;
    --secondary-color: #6c8eff;
    --background-gradient: linear-gradient(135deg, #f5f7ff 0%, #e8edff 100%);
    --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    --hover-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
    --success-color: #00c853;
    --warning-color: #ff9800;
    --error-color: #ff4757;
}

body {
    background: var(--background-gradient);
    min-height: 100vh;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    margin: 0;
    padding: 0;
}

/* 加载动画 */
.loading {
    display: none;
    text-align: center;
    padding: 2rem;
}

.loading-spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(74, 107, 255, 0.1);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 1s ease-in-out infinite;
    margin: 0 auto;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.card {
    border: none;
    border-radius: 16px;
    box-shadow: var(--card-shadow);
    transition: all 0.3s ease;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    margin-bottom: 2rem;
}

.card:hover {
    box-shadow: var(--hover-shadow);
    transform: translateY(-2px);
}

.card-header {
    background: transparent;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    padding: 1.5rem;
}

.card-header h3 {
    margin: 0;
    color: var(--primary-color);
    font-weight: 600;
}

.card-body {
    padding: 2rem;
}

/* 表单样式优化 */
.form-control, .form-select {
    border-radius: 12px;
    border: 1px solid rgba(0, 0, 0, 0.1);
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
    font-size: 1rem;
}

.form-control:focus, .form-select:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(74, 107, 255, 0.15);
}

.form-label {
    font-weight: 500;
    margin-bottom: 0.5rem;
    color: #333;
}

.form-text {
    color: #666;
    font-size: 0.875rem;
    margin-top: 0.25rem;
}

/* 按钮样式优化 */
.btn-primary {
    background: var(--primary-color);
    border: none;
    border-radius: 12px;
    padding: 0.75rem 1.5rem;
    font-weight: 500;
    transition: all 0.3s ease;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.btn-primary:hover {
    background: var(--secondary-color);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(74, 107, 255, 0.3);
}

/* 表格样式优化 */
.table {
    border-radius: 12px;
    overflow: hidden;
    margin-bottom: 0;
}

.table th {
    text-align: center;
    vertical-align: middle;
    font-size: 0.9rem;
    font-weight: 600;
    background: rgba(74, 107, 255, 0.05);
    border-bottom: 2px solid rgba(0, 0, 0, 0.05);
    padding: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
    width: 1%;
}

.table td {
    font-size: 0.9rem;
    vertical-align: middle;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    padding: 1rem;
}

.table-hover tbody tr {
    cursor: pointer;
    transition: all 0.3s ease;
}

.table-hover tbody tr:hover {
    background: rgba(74, 107, 255, 0.05);
    transform: translateX(5px);
}

/* 状态标签样式 */
.status-tag {
    display: inline-block;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.status-success {
    background: rgba(0, 200, 83, 0.1);
    color: var(--success-color);
}

.status-warning {
    background: rgba(255, 152, 0, 0.1);
    color: var(--warning-color);
}

.status-error {
    background: rgba(255, 71, 87, 0.1);
    color: var(--error-color);
}

/* 响应式设计优化 */
@media (max-width: 768px) {
    .card {
        margin: 1rem;
    }
    
    .card-body {
        padding: 1.5rem;
    }
    
    .table-responsive {
        margin: 0 -1rem;
    }
    
    .table th, .table td {
        padding: 0.75rem;
        font-size: 0.85rem;
    }
    
    .btn-primary {
        width: 100%;
    }
    
    .form-control, .form-select {
        font-size: 16px; /* 防止iOS自动缩放 */
    }
}

/* 动画效果 */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.animate-fade-in {
    animation: fadeIn 0.5s ease-out forwards;
}

/* 快递公司图标 */
.carrier-icon {
    width: 24px;
    height: 24px;
    margin-right: 8px;
    vertical-align: middle;
}

/* 历史记录时间样式 */
.query-time {
    color: #666;
    font-size: 0.85rem;
}

/* 操作按钮样式 */
.action-btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.85rem;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.action-btn:hover {
    transform: translateY(-1px);
}

/* 弹窗样式优化 */
#sf-modal-bg {
    position: fixed;
    left: 0; top: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.3);
    backdrop-filter: blur(5px);
    z-index: 2000;
    display: none;
    animation: fadeIn 0.3s ease-out;
}

#sf-modal {
    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    border-radius: 16px;
    box-shadow: var(--card-shadow);
    padding: 2rem 1.5rem 1.5rem 1.5rem;
    z-index: 2100;
    min-width: 260px;
    max-width: 90vw;
    display: none;
    animation: fadeIn 0.3s ease-out;
}

#sf-modal input {
    text-align: center;
    font-size: 1.2rem;
    letter-spacing: 0.2em;
    border-radius: 12px;
    padding: 1rem;
}

/* 错误提示样式 */
.error-message {
    color: var(--error-color);
    font-size: 0.9rem;
    margin-top: 0.5rem;
    display: none;
}

/* 成功提示样式 */
.success-message {
    color: var(--success-color);
    font-size: 0.9rem;
    margin-top: 0.5rem;
    display: none;
}
</style>

<?php include 'header.php'; ?>

<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header">
                <h3 class="text-center">快递查询</h3>
            </div>
            <div class="card-body">
                <form method="POST" action="" id="queryForm" autocomplete="off">
                    <div class="mb-3">
                        <label for="tracking_number" class="form-label">快递单号</label>
                        <input type="text" class="form-control" id="tracking_number" name="tracking_number" required autocomplete="off">
                    </div>
                    <div class="mb-3">
                        <label for="carrier" class="form-label">快递公司（可选）</label>
                        <select class="form-select" id="carrier" name="carrier">
                            <option value="">自动识别</option>
                            <option value="zto">中通快递</option>
                            <option value="sto">申通快递</option>
                            <option value="yto">圆通快递</option>
                            <option value="yd">韵达快递</option>
                            <option value="sf">顺丰快递</option>
                            <option value="ems">EMS</option>
                        </select>
                        <div class="form-text">如果不选择快递公司，系统将自动识别</div>
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-primary">查询</button>
                    </div>
                </form>
                
                <?php if(isset($error)): ?>
                    <div class="alert alert-danger mt-3"><?php echo $error; ?></div>
                <?php endif; ?>
                
                <?php if(isset($result)): ?>
                    <div class="mt-4">
                        <h4>查询结果</h4>
                        <?php 
                        $carrier_name = '';
                        if (isset($result['result']['type'])) {
                            $carrier_code = strtolower($result['result']['type']);
                            $carrier_name = isset($carrier_map[$carrier_code]) ? $carrier_map[$carrier_code] : $result['result']['type'];
                        }
                        ?>
                        <div class="alert alert-info">
                            快递公司：<?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-striped mb-0">
                                <thead>
                                    <tr>
                                        <th>时间</th>
                                        <th>快递公司</th>
                                        <th>状态</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(isset($result['result']['list']) && is_array($result['result']['list'])): ?>
                                        <?php foreach($result['result']['list'] as $item): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($item['time']); ?></td>
                                                <td><?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?></td>
                                                <td><?php echo htmlspecialchars($item['status']); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="3" class="text-center">暂无物流信息</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if(isset($_SESSION['user_id']) && !empty($history)): ?>
                    <div class="mt-4">
                        <h4>最近查询</h4>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>单号</th>
                                        <th>快递公司</th>
                                        <th>状态</th>
                                        <th>查询时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $unique_history = array();
                                    foreach($history as $item) {
                                        $tracking_number = explode(':', $item['tracking_number'])[0];
                                        if (!isset($unique_history[$tracking_number])) {
                                            $unique_history[$tracking_number] = $item;
                                        }
                                    }
                                    foreach($unique_history as $item): 
                                        $carrier_name = '';
                                        if (!empty($item['carrier'])) {
                                            $carrier_code = strtolower($item['carrier']);
                                            $carrier_name = isset($carrier_map[$carrier_code]) ? $carrier_map[$carrier_code] : $item['carrier'];
                                        }
                                    ?>
                                        <tr onclick="window.location.href='index.php?tracking_number=<?php echo $item['tracking_number']; ?><?php if(!empty($item['carrier'])) echo '&carrier=' . urlencode($item['carrier']); ?>'">
                                            <td><?php echo explode(':', $item['tracking_number'])[0]; ?></td>
                                            <td><?php echo !empty($carrier_name) ? htmlspecialchars($carrier_name) : '未识别'; ?></td>
                                            <td class="history-status">
                                                <?php 
                                                $status = isset($item['status']) ? (string)$item['status'] : '暂无状态';
                                                if (mb_strlen($status, 'UTF-8') > 20) {
                                                    echo mb_substr($status, 0, 20, 'UTF-8') . '...';
                                                } else {
                                                    echo $status;
                                                }
                                                ?>
                                            </td>
                                            <td><?php echo $item['query_time']; ?></td>
                                            <td>
                                                <a href="history.php?delete=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('确定要删除这条记录吗？')">删除</a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 顺丰弹窗 -->
<div id="sf-modal-bg"></div>
<div id="sf-modal">
    <div class="mb-3 text-center">
        <strong>顺丰快递需要输入手机号后四位</strong>
    </div>
    <input type="text" id="sf-phone" maxlength="4" class="form-control mb-3" placeholder="请输入手机号后四位">
    <div class="d-grid">
        <button class="btn btn-primary" id="sf-confirm">确定</button>
    </div>
</div>
<script>
const form = document.getElementById('queryForm');
const carrierSelect = document.getElementById('carrier');
const trackingInput = document.getElementById('tracking_number');
const sfModalBg = document.getElementById('sf-modal-bg');
const sfModal = document.getElementById('sf-modal');
const sfPhone = document.getElementById('sf-phone');
const sfConfirm = document.getElementById('sf-confirm');
let sfRequired = false;
let sfPhoneValue = '';

function isSF(tracking, carrier) {
    return carrier === 'sf' || (carrier === '' && /^SF\d+/i.test(tracking));
}

function showSFModal() {
    sfModalBg.style.display = 'block';
    sfModal.style.display = 'block';
    sfPhone.value = '';
    sfPhone.focus();
}
function hideSFModal() {
    sfModalBg.style.display = 'none';
    sfModal.style.display = 'none';
}

// 监听单号和快递公司输入，自动弹窗
trackingInput.addEventListener('blur', function() {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier) && !sfRequired) {
        sfRequired = true;
        showSFModal();
    }
});
carrierSelect.addEventListener('change', function() {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier) && !sfRequired) {
        sfRequired = true;
        showSFModal();
    }
});

sfConfirm.onclick = function() {
    const phone = sfPhone.value.trim();
    if (!/^\d{4}$/.test(phone)) {
        sfPhone.classList.add('is-invalid');
        sfPhone.focus();
        return;
    }
    sfPhone.classList.remove('is-invalid');
    sfPhoneValue = phone;
    hideSFModal();
    // 触发表单提交
    form.requestSubmit();
};
// 点击遮罩关闭弹窗
sfModalBg.onclick = function() {
    hideSFModal();
};

// 表单提交时，顺丰自动拼接后四位，提交后还原
form.addEventListener('submit', function(e) {
    const tracking = trackingInput.value.trim();
    const carrier = carrierSelect.value;
    if (isSF(tracking, carrier)) {
        if (!sfPhoneValue) {
            // 没有输入后四位，弹窗
            e.preventDefault();
            showSFModal();
            return;
        }
        // 拼接后四位，提交
        trackingInput.value = tracking + ':' + sfPhoneValue;
        setTimeout(() => {
            trackingInput.value = tracking; // 提交后还原
            sfPhoneValue = '';
            sfRequired = false;
        }, 100);
    } else {
        sfPhoneValue = '';
        sfRequired = false;
    }
});

// 添加输入框自动补全
document.addEventListener('DOMContentLoaded', function() {
    const trackingInput = document.getElementById('tracking_number');
    const carrierSelect = document.getElementById('carrier');
    
    // 自动补全历史记录
    if (trackingInput) {
        trackingInput.addEventListener('input', function() {
            const value = this.value.trim();
            if (value.length > 0) {
                // 这里可以添加自动补全逻辑
            }
        });
    }
    
    // 快递单号实时验证
    if (trackingInput) {
        trackingInput.addEventListener('blur', function() {
            const value = this.value.trim();
            if (value.length > 0 && !/^[A-Za-z0-9]+$/.test(value)) {
                showError(this, '请输入有效的快递单号');
            } else {
                hideError(this);
            }
        });
    }
    
    // 显示加载动画
    const form = document.getElementById('queryForm');
    if (form) {
        form.addEventListener('submit', function() {
            showLoading();
        });
    }
});

function showLoading() {
    const loading = document.createElement('div');
    loading.className = 'loading';
    loading.innerHTML = '<div class="loading-spinner"></div><p>正在查询中...</p>';
    document.querySelector('.card-body').appendChild(loading);
}

function showError(input, message) {
    let errorDiv = input.nextElementSibling;
    if (!errorDiv || !errorDiv.classList.contains('error-message')) {
        errorDiv = document.createElement('div');
        errorDiv.className = 'error-message';
        input.parentNode.insertBefore(errorDiv, input.nextSibling);
    }
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    input.classList.add('is-invalid');
}

function hideError(input) {
    const errorDiv = input.nextElementSibling;
    if (errorDiv && errorDiv.classList.contains('error-message')) {
        errorDiv.style.display = 'none';
    }
    input.classList.remove('is-invalid');
}
</script>

<?php include 'footer.php'; ?> 